define(function(require, exports, module) {
	
	var win = require("window");

	require("plugins/poshytip/tip-twitter/tip-twitter.css");
	require("plugins/poshytip/jquery.poshytip.min.js");

	var $ = jQuery;

	//页面底栏
	var MenuBar = function(container, menus) {

		var _this = this;
		var menuBar = $('<div class="menu-bar"></div>').appendTo(container);
		$('<div class="menu-bar-bg"></div>').appendTo(menuBar);
		var menuButtons = $('<div class="menu-buttons"></div>').appendTo(menuBar);
		var buttons = [];
		var moreButtons = [];
		var moreButtonData = {
			type:0,
			isNoTile:true,
			icon:"res/images/icons/more.png",
			name:$.i18n.prop("info.more.funcs"),
			router:"index/more",
			shade:0.3,
			shadeClose:true,
			max:false,
			closeBtn:false,
			btn:false,
			content:'<div class="folder-border"><div class="content box"></div></div>',
			skin:'layui-layer-msg layui-layer-hui',
			area:['540px', '322px'],
			params: {
				buttons:moreButtons,
				onButtonsChanged:function() {}
			},
			success:function(layero, win) {
				$(layero).on("click.more", function() {
					win.close();
				});
			}
		};
		var moreButton = new MenuButton(moreButtonData);

		$(menus).each(function() {
			buttons.push(new MenuButton(this));
		});

		this.destroyButtons = function() {
			$(buttons).each(function() {
				this.destroy();
			});
			moreButton.destroy();
			moreButtons.splice(0, moreButtons.length);
		}

		this._rebuild = function() {
			var barwidth = menuBar.innerWidth() -
				parseInt(menuButtons.css("padding-left").replace("px")) -
				parseInt(menuButtons.css("padding-right").replace("px"));
			var barMaxSize = 1;
			var hasMore = false;
			//清除图标
			this.destroyButtons();
			$(buttons).each(function(index) {
				if(index < barMaxSize) {
					this.init(menuButtons);
				} else {
					moreButtons.push(this);
				}
				if(index == 0) {
					barMaxSize = parseInt(barwidth / this.getWidth());
					if(buttons.length > barMaxSize) {
						barMaxSize --;
						hasMore = true;
					}
				}
			});
			moreButtonData.params.onButtonsChanged();
			if(hasMore) {
				moreButton.init(menuButtons);
			}
		}

		this.destroy = function() {
			this.destroyButtons();
			$(window).off("resize.menubar");
		}
		
		$(window).on("resize.menubar", function() {
			_this._rebuild();
		});

		$(window).triggerHandler("resize.menubar");
	};

	//首页底栏按钮
	var MenuButton = function(options, onButtonClicked) {

		var item = null;
		var icon = null;
		var reflection = null;
		var win = null;
		var opening = false;
		var opts = {};
		var buttonClicked = onButtonClicked ? onButtonClicked : function(win) {};

		$.extend(opts, options);

		if(!opts.icon) {
			throw "需要一个图标地址（icon）！";
		}
		if(!opts.name && !opts.i18n) {
			throw "需要一个名称（name）！";
		}
		if(!opts.router && (!opts.children || opts.children.length == 0)) {
			throw "需要一个路由（router）！";
		}

		var children = [];
		if(opts.children && opts.children.length > 0) {
			var onChildrenButtonClicked = function() {
				win.close();
			}
			$(opts.children).each(function() {
				children.push(new MenuButton(this, onChildrenButtonClicked));
			});
		}
		function onItemClick(beginOpenWindow, finishOpenWindow) {
			if(win) {
				//存在窗口，直接显示
				win.show();
			} else {
				if(beginOpenWindow()) {
					if(children.length > 0) {
					    var currentOptions = {};
						var defaultOptions = {
							title:"",
							router:"index/folder",
							shade:0.3,
							shadeClose:true,
							max:false,
							closeBtn:false,
							btn:false,
							icon:-1,
							content:'<div class="folder-border"><div class="content box"></div></div>',
							skin:'layui-layer-msg layui-layer-hui',
							area:['540px', '322px'],
							success:function(layero) {
								if(typeof(opts.success) == "function") {
									opts.success.call(this, layero, win);
								}
								finishOpenWindow();
							},
							error:function() {
								if(typeof(opts.error) == "function") {
									opts.error.call(this);
								}
								finishOpenWindow();
							},
							end:function() {
								if(typeof(opts.end) == "function") {
									opts.end.call(this);
								}
								win = null;
							}
						};
						$.extend(currentOptions, opts);
						$.extend(currentOptions, defaultOptions);
						//根据路由创建窗口
						win = $.window(currentOptions, {buttons:children});
					} else {
						var currentOptions = {};
						var defaultOptions = {
							title:opts.isNoTile == true ? "" : (opts.i18n ? $.i18n.prop(opts.i18n) : opts.name),
							router:opts.router,
					        max:opts.max == false ? false : true,
					        icon:-1,
							success:function(layero) {
								if(typeof(opts.success) == "function") {
									opts.success.call(this, layero, win);
								}
								finishOpenWindow();
							},
							error:function() {
								if(typeof(opts.error) == "function") {
									opts.error.call(this);
								}
								finishOpenWindow();
							},
							end:function() {
								if(typeof(opts.end) == "function") {
									opts.end.call(this);
								}
								win = null;
							}
						};
						$.extend(currentOptions, opts);
						$.extend(currentOptions, defaultOptions);
						//根据路由创建窗口
						win = $.window(currentOptions, opts.params);
					}
				}
			}
			buttonClicked(win);
		};

		this.init = function(container) {
			var title = opts.i18n ? $.i18n.prop(opts.i18n) : opts.name;
			item = $('<div class="menu-button" title="' + title + '"></div>').appendTo(container);
			item.poshytip({
				className: 'tip-twitter',
				showTimeout: 1,
				alignTo: 'target',
				alignX: 'center',
				offsetY: 5,
				allowTipHover: false,
				fade: false,
				slide: false
			});
			var url = "url(" + $.toUrl(opts.icon) + ")";
			//图标
			icon = $('<div class="menu-icon">&nbsp;</div>').appendTo(item);
			icon.css("background-image", url);
			//倒影
			reflection = $('<div class="reflection">&nbsp;</div>').appendTo(item);
			reflection.css("background-image", url);
			function beginOpenWindow() {
				if(!opening) {
					opening = true;
					//动画
					icon.addClass("menu-icon-animate");
					reflection.addClass("reflection-animate");
					return true;
				}
				return false;
			}

			function finishOpenWindow() {
				opening = false;
				icon.removeClass("menu-icon-animate");
				reflection.removeClass("reflection-animate");
			}
			
			item.on("click.menubutton", function() {
				onItemClick(beginOpenWindow, finishOpenWindow);
			});
		};

		this.initIcon = function(container) {
			var title = opts.i18n ? $.i18n.prop(opts.i18n) : opts.name;
			item = $('<li><i></i><div>'+title+'</div></li>').appendTo(container);
			var url = "url(" + $.toUrl(opts.icon) + ")";
			item.children("i").css("background-image", url);

			function beginOpenWindow() {
				if(!opening) {
					opening = true;
					return true;
				}
				return false;
			}

			function finishOpenWindow() {
				opening = false;
			}
			
			item.on("click.menubutton",  function() {
				onItemClick(beginOpenWindow, finishOpenWindow);
			});
		};

		this.destroy = function() {
			if(item) {
				item.off("click.menubutton");
				item.poshytip('destroy');
				item.remove();
				icon = null;
				reflection = null;
				item = null;
				opening = false;
			}
		}

		this.getWidth = function() {
			return item.outerWidth() + 
				parseInt(item.css("margin-left").replace("px")) + 
				parseInt(item.css("margin-right").replace("px"));
		}

		this.getWindow = function() {
			return win;
		}

	};

	$.fn.extend({

		indexMenuBar:function(menus) {
			var _this = this[0];
			var menuBar = $(_this).data("_indexMenuBar");
			if(!menuBar) {
				menuBar = new MenuBar(_this, menus);
			}
			return menuBar;
		},
		hasIndexMenuBar: function() {
			return !!$(_this).data("_indexMenuBar");
		}

	});

	module.exports = {
		build:function(selector, menus) {
			return $(selector).indexMenuBar(menus);
		},
		hasMenuBar:function(selector) {
			return $(selector).hasIndexMenuBar();
		}
	};

});